

package com.yl.zqy.utils;

import com.yl.zqy.common.CustomException;
import com.yl.zqy.common.MemoryCache;
import com.yl.zqy.entity.sys.SysDictData;
import com.yl.zqy.enums.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 转换工具类
 *
 * @author Mark sunlightcs@gmail.com
 */
public class ConvertUtils {
    private static Logger logger = LoggerFactory.getLogger(ConvertUtils.class);


    public static <T> T sourceToTarget(Object source, Class<T> target) {
        if (source == null) {
            return null;
        }
        T targetObject = null;
        try {
            targetObject = target.newInstance();
            BeanUtils.copyProperties(source, targetObject);
        } catch (Exception e) {
            logger.error("convert error ", e);
            throw new CustomException(ResultCode.UNKNOW_ERROR);
        }

        return targetObject;
    }

    public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target) {
        if (sourceList == null) {
            return null;
        }

        List targetList = new ArrayList<>(sourceList.size());
        try {
            for (Object source : sourceList) {
                T targetObject = target.newInstance();
                BeanUtils.copyProperties(source, targetObject);
                targetList.add(targetObject);
            }
        } catch (Exception e) {
            logger.error("convert error ", e);
            throw new CustomException(ResultCode.UNKNOW_ERROR);
        }

        return targetList;
    }

    public static Map<String, Object> convertObjectToMap(Object obj) throws Exception {
        Map<String, Object> map = new HashMap();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }

    public static Map<String, String> getMemoryCacheByKey(String type) {
        return (Map<String, String>) MemoryCache.getInstance().getMemoryCacheMap().get(type);
    }

    public static Map<String, List<SysDictData>> getMemoryCacheListByKey(String type) {
        return (Map<String, List<SysDictData>>) MemoryCache.getInstance().getMemoryCacheMap().get(type);
    }
}